//
//  ShareView.swift
//  MMShareServiceDemo
//
//  Created by 吴传荣 on 2021/5/27.
//

import UIKit
import SnapKit

public class ShareView: UIView {
    
    let screenHeight: CGFloat = UIScreen.main.bounds.size.height
    let screenWidth: CGFloat = UIScreen.main.bounds.size.width
    
    let lrBorder: CGFloat = 20
    
    private var showScenes: [ShareSceneType] = []
    private var messageModel: ShareMessageModel!
    
    @IBOutlet weak var bgView: UIView!

    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var contentViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var cancelButton: UIButton!
    @IBOutlet weak var cancelButtonBottom: NSLayoutConstraint!
    
    public override func awakeFromNib() {
        super.awakeFromNib()
        
        contentView.layer.cornerRadius = 15
        cancelButtonBottom.constant = -screenHeight
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick(_:)))
        bgView.addGestureRecognizer(tap)
    }
    
    
    @IBAction func cancelAction(_ sender: UIButton) {
        dismiss()
    }
    
}

// MARK: Setup UI
extension ShareView {
    
    private func setupSubViews() {
        
        contentView.subviews.forEach({ $0.removeFromSuperview() })
        
        let infos:[(String, String, Int)] = showScenes.map { [weak self] scene in
            guard let `self` = self else { return ("", "", 0) }
            return self.getSceneInfo(scene)
        }
        
        let itemBorder: CGFloat = 20
        let itemTop: CGFloat = 20
        
        var itemTopBorder = itemTop
        var itemLeftBorder = itemBorder
        // 展示4个
        let imageWH: CGFloat = (min(screenWidth, screenHeight) - lrBorder * 2 - itemBorder * 5) / 4.0
        // label高度
        let font = UIFont.systemFont(ofSize: 13)
        let labelHeight: CGFloat = font.lineHeight * 2 + 5
        
        // 每个item的宽高
        let labelImageSpace: CGFloat = 10
        let itemWidth = imageWH
        let itemHeight = imageWH + labelImageSpace + labelHeight
        
        var tempContentHeight: CGFloat = 0
        
        for index in 0..<infos.count {
            
            let (imageName, title, tag) = infos[index]
            
            let control = UIControl()
            control.tag = tag
            control.addTarget(self, action: #selector(clickScencControl(_:)), for: .touchUpInside)
            contentView.addSubview(control)
            control.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(itemLeftBorder)
                make.top.equalToSuperview().offset(itemTopBorder)
                make.size.equalTo(CGSize(width: itemWidth, height: itemHeight))
            }
            
            let imageView = UIImageView(image: UIImage(named: imageName))
            imageView.contentMode = .scaleAspectFit
            control.addSubview(imageView)
            
            let label = UILabel()
            label.font = font
            label.textAlignment = .center
            label.text = title
            control.addSubview(label)
            
            imageView.snp.makeConstraints { make in
                make.left.top.right.equalToSuperview()
                make.height.equalTo(imageWH)
            }
            
            label.snp.makeConstraints { make in
                make.left.right.equalTo(imageView)
                make.top.equalTo(imageView.snp.bottom).offset(labelImageSpace)
                make.bottom.equalToSuperview()
            }
            
            itemLeftBorder += itemWidth + itemBorder
            tempContentHeight = itemTopBorder + itemHeight + itemTop
            // 换行
            if (index + 1) % 4 == 0 {
                itemTopBorder += itemHeight + itemTop
                itemLeftBorder = itemBorder
            }
        }
        
        contentViewHeight.constant = tempContentHeight
        cancelButtonBottom.constant = -(contentViewHeight.constant + 150)
        layoutIfNeeded()
    }
}

// MARK: event
extension ShareView {
    
    @objc private func tapClick(_ tap: UITapGestureRecognizer) {
        dismiss()
    }
    
    @objc private func clickScencControl(_ control: UIControl) {
        let scene: ShareSceneType = ShareSceneType(rawValue: control.tag) ?? .WXSceneSession
        messageModel.shareSceneType = scene
        ShareManager.manager.shareAction(with: messageModel)
        dismiss()
    }
    
}

// MARK: Util
extension ShareView {
    private func getSceneInfo(_ sceneType: ShareSceneType) -> (imageName: String, title: String, tag: Int) {
        switch sceneType {
        case .WXSceneSession:
            return ("share_wechat", "微信好友", sceneType.rawValue)
        case .WXSceneTimeline:
            return ("share_wechat_timeline", "微信朋友圈", sceneType.rawValue)
        case .WXSceneFavorite:
            return ("share_wechat_collection", "微信收藏", sceneType.rawValue)
        }
    }
}

// MARK: Public Method
extension ShareView {
    
    /// 默认加到window上
    public static func showShareView(scenes: [ShareSceneType] = [.WXSceneSession],
                                     messageModel: ShareMessageModel,
                                     showView: UIView = (UIApplication.shared.keyWindow ?? UIWindow())) {
        let bundle = Bundle(for: Self.self)
        guard let shareView = bundle.loadNibNamed("ShareView", owner: nil, options: nil)?.first as? ShareView else {
            return
        }
        
        if shareView.isDescendant(of: showView) { return }
        
        showView.addSubview(shareView)
        shareView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        shareView.pop(scenes, messageModel)
    }
    
    public func pop(_ scenes: [ShareSceneType] = [.WXSceneSession], _ messageModel: ShareMessageModel) {
        
        showScenes = scenes
        self.messageModel = messageModel
        
        setupSubViews()
        let window = UIApplication.shared.keyWindow
        let bottomPadding = window?.safeAreaInsets.bottom ?? 0
        cancelButtonBottom.constant = 10 + bottomPadding
        
        UIView.animate(withDuration: 0.3) { [weak self] in
            guard let `self` = self else { return }
            self.layoutIfNeeded()
        }
    }
    
    public func dismiss() {
        cancelButtonBottom.constant = -screenHeight
        UIView.animate(withDuration: 0.3) { [weak self] in
            guard let `self` = self else { return }
            self.layoutIfNeeded()
            self.alpha = 0
        } completion: { [weak self] finish in
            guard let `self` = self else { return }
            self.removeFromSuperview()
        }
    }
    
}


